package com.newdjk.okhttp;

import android.text.TextUtils;
import android.util.Log;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/*
 *  @项目名：  RetrofitRxjavaDemo
 *  @包名：    com.example.huhai.retrofitrxjavademo.net
 *  @文件名:   InterceptorUtil
 *  @创建者:   EDZ
 *  @创建时间:  2018/11/1 10:46
 *  @描述：
 */
public class InterceptorUtil {
    public static String TAG = "http";

    //日志拦截器
    public static HttpLoggingInterceptor LogInterceptor() {
        return new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.w(TAG, "log: " + message);
            }
        }).setLevel(HttpLoggingInterceptor.Level.BODY);//设置打印数据的级别
    }

    public static Interceptor HeaderInterceptor(final String token) {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request mRequest = chain.request();
                //在这里你可以做一些想做的事,比如token失效时,重新获取token
                //或者添加header等等
//                HashMap<String, String> headersMap = new HashMap<>();
//                 headersMap.put("Access-Client", "APP");
//        headersMap.put("Access-RegistrationId", "123121111111222222222");
//        headersMap.put("Access-Platform", "Android");
                if (!TextUtils.isEmpty(RetrofitFactory.getToken())) {
                    Request request = mRequest.newBuilder()
                            .addHeader("Authorization", RetrofitFactory.getToken())//注入头信息
                            .build();
                    return chain.proceed(request);
                }

                return chain.proceed(mRequest);
            }
        };

    }

    /**
     * 获取头信息
     */
    private static Map<String, String> getHeaders() {
        HashMap<String, String> headersMap = new HashMap<>();
        // headersMap.put("Access-Client", "APP");
//        headersMap.put("Access-RegistrationId", "123121111111222222222");
//        headersMap.put("Access-Platform", "Android");
        return headersMap;
    }
}
